package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.OrderDetail;
import com.itheima.bean.Orders;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/2/25
 */
@Slf4j
@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartController shoppingCartController;


    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //1.调用service的提交订单方法
        ordersService.submit(orders);
        //2.返回结果
        return R.success("提交订单成功！");
    }

    /**
     * 移动端用户订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize) {
        log.info("订单分页查询数据:{}");
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        //条件构造器,添加过滤条件
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //查询当前用户的所有订单信息
        lambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());

        //保证查询数据的一致性,设置排序规则
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        Page data = ordersService.page(pageInfo, lambdaQueryWrapper);

        //然后把菜品信息注入进去
        List<Orders> records = data.getRecords();
        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(orderDetailList);
            //   ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        data.setRecords(list);
        return R.success(data);
    }

    /**
     * 管理端订单明细分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> userDetailPage(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        log.info("用户订单明细:{}", page, pageSize);
        //分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        //条件构造器,添加过滤条件
        LambdaQueryWrapper<Orders> queryWrap = new LambdaQueryWrapper<>();
        queryWrap.like(number != null, Orders::getId, number);
        queryWrap.ge(beginTime != null, Orders::getOrderTime, beginTime);
        queryWrap.le(endTime != null, Orders::getOrderTime, endTime);

        //设置排序规则
        queryWrap.orderByDesc(Orders::getCheckoutTime);

        //执行查询
        ordersService.page(pageInfo, queryWrap);


        //注入信息
        List<Orders> records = pageInfo.getRecords();
        records = records.stream().map((item) -> {
            item.setUserName("用户" + item.getUserId());
            return item;
        }).collect(Collectors.toList());

        //返回结果
        return R.success(pageInfo);
    }

    /**
     * 修改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> setStatus(@RequestBody Orders orders) {
        //将String转成Long
        log.info("订单正在派送{}", orders);
        ordersService.updateById(orders);
        return R.success("订单派送成功");
    }

    /**
     * 再来一单
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> againSubmit (@RequestBody Map<String,String> map){
        String ids = map.get("id");
        //获取订单id
        Long id = Long.parseLong(ids);

        //执行查询订单,获取订单对应的所有订单明细表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail :: getOrderId,id);

        //通过用户id把原来的购物车给清空
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        shoppingCartController.clean();

        //获取用户id,查询订单详情
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item)->{
            //把值重新赋值给购物车
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId != null){
                //查询是否是菜品
                shoppingCart.setDishId(dishId);
            }else {
                //查询是否是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            //补充其他信息
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //批量插入到购物车,返回结果
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("操作成功");
    }

}
